<template>
	<div class="hello">
		<!-- 左对齐 -->
		<van-row type="flex">
			<van-col span="6">
				<van-sidebar :active-key="activeKey" @change="onChange">
					<van-sidebar-item 
						:title="item.categoryName" 
						@click="onClick(item.categoryType)" 
						v-for="item in items" 
						:key="item.categoryType" />
				</van-sidebar>
			</van-col>
			<van-col span="19">
					<van-card 
						v-for="(product,index) in products" 
						:key="index" 
						:num="product.productQuantity" 
						:price="product.productPrice" 
						:desc="product.productDescription"
						:title="product.productName" 
						:thumb="/api/+product.productIcon">
						<div slot="footer">
							<van-stepper 
								@plus="onPlus(product)"
								@minus="onMinus(product)"
								v-model="product.productQuantity" 
								disable-input
								min="0" max="5" 
								@change="onChecked(product)" 
								integer />
						</div>
					</van-card>
			</van-col>
		</van-row>
		<van-submit-bar 
			:price="totalPrice" :disabled="productQuantity == 0" 
			:button-text="submitBarText" @submit="onSubmit" />

	</div>
</template>

<script>
	import wx from 'weixin-jsapi'
	export default {
		name: 'HelloWorld',
		data() {
			return {
				items: null, // 存储类别
				activeKey: 0,
				value: 0,
				products: [], // 存储商品
				key: 1,
				checkedGoods: [], // 选中商品
				map: null, // 商品选择数量， 防止切换类别清空选择商品数量
				price:0, // 总价格
				productQuantity: 0, // 选择商品的数量，（按照每个菜品来区分，跟每个商品的选择数量无关）
			}
		},
		created() { // 页面加载完成之后查询商品
			this.queryProduct();
		},
		computed: {
			submitBarText() { // 动态改变
				return '结算' + (this.productQuantity != 0 ? `(${this.productQuantity})` : '');
			},
			totalPrice() { //计算总价格
				let total = 0;
				let that = this;
				this.checkedGoods.forEach((product, index)=>{
					if (product.productQuantity == 0) {
						/* that.checkedGoods.splice(product.productId, 1);
						that.productQuantity --; */
						that.map.set(product.productId, 0);
					}
					total += product.productPrice * product.productQuantity;
				})
				that.price = total * 100;
				return total * 100;
			}
		},
		methods: {
			onPlus(product) { // 数量增加时
				if (product.productQuantity === 0) {
					this.productQuantity ++;
				}
			},
			queryProduct() { // 查询商品和类别
				this.$http.get(
					"/api/productInfo/queryProduct"
				).then(response => {
					this.items = response.data.data.category;
					this.products = response.data.data.products;
				}).catch(error => {

				}).finally(() => {

				});
			},
			onChange(key) { // 左侧导航栏选中切换
				this.activeKey = key;
			},
			onClick(type) {// 点击左侧导航栏
				// 防止重复点击
				if (this.key !== type) {
					// 区分不同的类别，分辨不同的菜品
					this.key = type;
					this.products = [];
					this.$http.get(
						"/api/productInfo/queryProductByType/" + type
					).then(response => {
						this.products = response.data.data;
						// 循环从数据库抓出来的数据
						this.products.forEach((pro, index) => {
							// 根据商品id去map里边取出对应的选择数量
							let productQuantity = this.map.get(pro.productId);
							// 判断取出的商品数量是否为 undefined 如果是就是0. 
							// 如果不是就代表之前选择过，直接将map中取出的数量赋给对象的数量
							pro.productQuantity = typeof(productQuantity) == 'undefined' ? 0 : productQuantity;
						});
					}).catch(error => {

					}).finally(() => {

					});
				}
			},
			onChecked(product) { //当选择了数量时
				if (typeof(this.map) == 'undefined' || this.map == null) {
					this.map = new Map();
				}
				let pro = this.checkedGoods[product.productId];
				if (typeof(pro) == 'undefined' || pro == null) {
					//this.checkedGoods[product.productId] = product;
					this.Vue.set(this.checkedGoods, product.productId, product);
				}
				this.map.set(product.productId, product.productQuantity);
				//this.totalPrice();
			},
			onSubmit() { // 提交按钮
				let goods = this.checkedGoods.notempty();
				this.$router.push({
					name:'createOrder',
					params: {
						goods,
						price: this.price
					}
				})
			},
			onMinus(product) { // 数量减少时
				this.Vue.set(this.checkedGoods, product.productId, product);
				if (product.productQuantity === 1) {
					this.productQuantity --;
				}
				//this.totalPrice();
			}
		},
	}
	Array.prototype.notempty = function() {
    var arr = [];
    this.map(function(val, index) {
        //过滤规则为，不为空串、不为null、不为undefined，也可自行修改
        if ((val !== "" && typeof(val) != 'undefined') && val.productQuantity != 0) {
            arr.push(val);
        }
    });
    return arr;
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
